import { ref, watch, computed, nextTick, getCurrentInstance, onMounted } from 'vue';
import type { Ref } from 'vue';
import { sleep, getRect, isString } from '../../../libs/utils';
import { getPx } from '../../../libs/utils/_utils';
import { delay, getTouch } from '../utils';
import type { hooksParam, CommonState } from '.';
import { Enum } from '../env';
import useNVue from './nvue';

// #ifdef APP-NVUE
const weexAnimation = weex.requireModule('animation');
// #endif

// 添加单位
const _addUnit = (value?: string | number, unit?: string) => {
	if (isString(value)) {
		let tempValue: string | number = value;
		tempValue = tempValue.replace('rpx', '').replace('upx', '').replace('px', '');
		if (value.indexOf('rpx') === -1 && value.indexOf('upx') === -1 && value.indexOf('px') !== -1) {
			tempValue = parseFloat(tempValue) * 2;
		}
		value = tempValue;
	}
	return unit === 'rpx' ? value + 'rpx' : Number(value) / 2 + 'px';
};

const useRefresher = (
	ctx: ReturnType<typeof getCurrentInstance>,
	option: Ref<hooksParam>,
	emit: ReturnType<typeof defineEmits>,
	commonState: CommonState,
	refresherEnd: Function,
	oldScrollTop: Ref<number>,
	pageScrollTop: Ref<number>,
	doChatRecordLoadMore: Function
) => {
	const finalRefresherEnabled = computed(() => {
		if (option.value.useChatRecordMode) return false;
		if (privateRefresherEnabled.value === -1) return option.value.refresherEnabled;
		return privateRefresherEnabled.value === 1;
	});

	const showF2 = ref(false);
	const f2Transform = ref('');
	const f2ElRef = ref();
	const nF2Opacity = ref(0);

	// 处理进入二楼
	const handleGoF2 = () => {
		if (showF2.value || !option.value.refresherF2Enabled) return;
		emit('refresherF2Change', 'go');

		if (!option.value.showRefresherF2) return;
		// #ifndef APP-NVUE
		f2Transform.value = `translateY(${-commonState.superContentHeight}px)`;
		showF2.value = true;
		delay(
			() => {
				f2Transform.value = 'translateY(0px)';
			},
			100,
			'f2ShowDelay'
		);
		// #endif

		// #ifdef APP-NVUE
		showF2.value = true;
		nextTick(() => {
			weexAnimation.transition(f2ElRef.value, {
				styles: { transform: `translateY(${-commonState.superContentHeight}px)` },
				duration: 0,
				timingFunction: 'linear',
				needLayout: true,
				delay: 0
			});
			nF2Opacity.value = 1;
		});
		delay(
			() => {
				weexAnimation.transition(f2ElRef.value, {
					styles: { transform: 'translateY(0px)' },
					duration: option.value.refresherF2Duration,
					timingFunction: 'linear',
					needLayout: true,
					delay: 0
				});
			},
			10,
			'f2GoDelay'
		);
		// #endif
	};

	// 处理退出二楼
	const _handleCloseF2 = () => {
		if (!showF2.value || !option.value.refresherF2Enabled) return;
		emit('refresherF2Change', 'close');

		if (!option.value.showRefresherF2) return;
		// #ifndef APP-NVUE
		f2Transform.value = `translateY(${-commonState.superContentHeight}px)`;
		// #endif

		// #ifdef APP-NVUE
		weexAnimation.transition(f2ElRef.value, {
			styles: { transform: `translateY(${-commonState.superContentHeight}px)` },
			duration: option.value.refresherF2Duration,
			timingFunction: 'linear',
			needLayout: true,
			delay: 0
		});
		// #endif

		delay(
			() => {
				showF2.value = false;
				nF2Opacity.value = 0;
			},
			Number(option.value.refresherF2Duration),
			'f2CloseDelay'
		);
	};
	// 关闭二楼
	const closeF2 = () => {
		_handleCloseF2();
	};
	const isRefresherInComplete = ref(false);
	const refresherTriggered = ref<boolean | string>(false);
	// 自定义下拉刷新被触发
	const handleRefresh = (fromScrollView = false, _isUserPullDown = true) => {
		emit('refresh');
		if (fromScrollView && !(finalRefresherEnabled.value && !option.value.useCustomRefresher)) return;

		if (isRefresherInComplete.value) return;

		refresherTriggered.value = true;
	};

	const finalRefresherDefaultStyle = ref('#777777');

	watch(
		() => option.value.defaultThemeColor,
		(v) => {
			if (v) {
				finalRefresherDefaultStyle.value = v;
			}
		},
		{
			immediate: true
		}
	);
	watch(
		() => option.value.refresherDefaultColor,
		(v) => {
			if (v) {
				finalRefresherDefaultStyle.value = v;
			}
		},
		{
			immediate: true
		}
	);

	// 触发下拉刷新
	const _doRefresherLoad = (_isUserPullDown = true) => {
		handleRefresh(false, _isUserPullDown);
	};

	let oldPullingDistance = -1;
	// emit pullingDown事件
	const _emitTouchmove = (e: { pullingDistance: number; dy: number; viewHeight?: number; rate?: number }) => {
		// #ifndef APP-NVUE
		e.viewHeight = finalRefresherThreshold.value;
		// #endif
		e.rate = e.viewHeight! > 0 ? e.pullingDistance / e.viewHeight! : 0;
		option.value.watchRefresherTouchmove && oldPullingDistance !== e.pullingDistance && emit('refresherTouchmove', e);
		oldPullingDistance = e.pullingDistance;
	};

	// 更新下拉刷新状态
	const checkRefresherStatus = (beyond: boolean, value: number) => {
		// 下拉刷新距离超过阈值
		if (beyond) {
			let status = false;
			// #ifndef APP-NVUE
			status = !!(option.value.refresherF2Enabled && value >= finalRefresherF2Threshold.value);
			// #endif
			// #ifdef APP-NVUE
			// value + finalRefresherThreshold.value 不等同于pullingDistance，此处是为了兼容不同平台下拉相同距离pullingDistance不一致的问题，pullingDistance仅与viewHeight互相关联
			status = !!(option.value.refresherF2Enabled && value + finalRefresherThreshold.value >= finalRefresherF2Threshold.value);
			// #endif
			// 如果开启了下拉进入二楼并且下拉刷新距离超过进入二楼阈值，则当前下拉刷新状态为松手进入二楼，否则为松手立即刷新
			commonState.refresherStatus = status ? Enum.Refresher.GoF2 : Enum.Refresher.ReleaseToRefresh;
		} else {
			// 下拉刷新距离未超过阈值，显示默认状态
			commonState.refresherStatus = Enum.Refresher.Default;
		}
	};

	// #ifdef APP-NVUE
	const {
		nLoadingMoreFixedHeight,
		finalNvueListIs,
		nWaterfallColumnCount,
		nWaterfallColumnWidth,
		nWaterfallColumnGap,
		nWaterfallLeftGap,
		nWaterfallRightGap,
		nViewIs,
		finalNvueSuperListIs,
		finalNvueRefresherEnabled,
		handleNVueScroll,
		nListRef,
		_nRefresherEnd,
		nRefresherLoading,
		_nOnRrefresh,
		_nOnPullingdown,
		_nDoRefresherEndAnimation,
		handleNVueLoadmore,
		_nGetWaterfallConfig
	} = useNVue(
		ctx,
		option,
		emit,
		commonState,
		refresherEnd,
		{
			finalRefresherEnabled,
			handleGoF2,
			_doRefresherLoad,
			_emitTouchmove,
			checkRefresherStatus
		},
		oldScrollTop,
		doChatRecordLoadMore
	);
	// #endif
	const pullDownDisTimeStamp = computed(() => {
		return 1000 / Number(option.value.refresherFps);
	});
	const privateRefresherEnabled = ref(-1);
	const refresherThresholdUnitConverted = computed(() => {
		return _addUnit(option.value.refresherThreshold, option.value.unit);
	});

	const finalRefresherThresholdPlaceholder = computed(() => {
		return option.value.useRefresherStatusBarPlaceholder ? commonState.systemInfo.statusBarHeight || 0 : 0;
	});
	const finalRefresherThreshold = computed(() => {
		let refresherThreshold = refresherThresholdUnitConverted.value;
		let idDefault = false;
		if (refresherThreshold === _addUnit(80, option.value.unit)) {
			idDefault = true;
			if (option.value.refresherTimeText) {
				refresherThreshold = _addUnit(120, option.value.unit);
			}
		}
		if (idDefault && customRefresherHeight.value > 0) return customRefresherHeight.value + finalRefresherThresholdPlaceholder.value;
		return getPx(refresherThreshold) + finalRefresherThresholdPlaceholder.value;
	});
	const finalRefresherF2Threshold = computed(() => {
		return getPx(_addUnit(option.value.refresherF2Threshold, option.value.unit));
	});

	const finalRefresherFixedBacHeight = computed(() => {
		return getPx(option.value.refresherFixedBacHeight);
	});
	const finalRefresherThemeStyle = computed(() => {
		return option.value?.refresherThemeColor || option.value.defaultThemeColor;
	});
	const finalRefresherOutRate = computed(() => {
		let rate = option.value.refresherOutRate;
		rate = Math.max(0, rate);
		rate = Math.min(1, rate);
		return rate;
	});
	const finalRefresherPullRate = computed(() => {
		let rate = option.value.refresherPullRate;
		rate = Math.max(0, rate);
		return rate;
	});
	const finalRefresherTransform = computed(() => {
		if (option.value.refresherNoTransform || refresherTransform.value === 'translateY(0px)') return 'none';
		return refresherTransform.value;
	});

	const finalRefresherTriggered = computed(() => {
		if (!(finalRefresherEnabled.value && !option.value.useCustomRefresher)) return false;
		return refresherTriggered.value;
	});
	const showRefresher = computed(() => {
		return finalRefresherEnabled.value && option.value.useCustomRefresher;
	});

	// 使手机发生较短时间的振动（15ms）
	const doVibrateShort = () => {
		// #ifndef H5

		// #ifdef APP-PLUS
		if (commonState.isIos) {
			const UISelectionFeedbackGenerator = plus.ios.importClass('UISelectionFeedbackGenerator');
			const feedbackGenerator = new UISelectionFeedbackGenerator();
			feedbackGenerator.init();
			setTimeout(() => {
				feedbackGenerator.selectionChanged();
			}, 0);
		} else {
			plus.device.vibrate(15);
		}
		// #endif
		// #ifndef APP-PLUS
		uni.vibrateShort();
		// #endif

		// #endif
	};
	watch(
		() => commonState.refresherStatus,
		(v) => {
			v === Enum.Refresher.Loading && commonState.cleanRefresherEndTimeout();
			option.value.refresherVibrate && (v === Enum.Refresher.ReleaseToRefresh || v === Enum.Refresher.GoF2) && doVibrateShort();
			emit('refresherStatusChange', v);
			emit('update:refresherStatus', v);
		}
	);

	const refresherTransform = ref('translateY(0px)');

	const refresherRevealStackCount = ref(0);

	let isTouchmovingTimeout: number;

	const isTouchmoving = ref(false);

	const customRefresherHeight = ref(-1);
	const showCustomRefresher = ref(false);
	const doRefreshAnimateAfter = ref(false);

	let moveDis = 0;
	let oldMoveDis = 0;

	// 自定义下拉刷新被复位
	const _onRestore = () => {
		refresherTriggered.value = 'restore';
		emit('restore');
	};
	const loading = ref(false);
	let loadingType = Enum.LoadingType.Refresher;
	let refresherCompleteSubTimeout: number | undefined;
	// 下拉刷新结束
	const _refresherEnd = (shouldEndLoadingDelay = true, fromAddData = false, isUserPullDown = false, setLoading = true) => {
		if (loadingType === Enum.LoadingType.Refresher) {
			const refresherCompleteDelay = fromAddData && isUserPullDown ? Number(option.value.refresherCompleteDelay) : 0;
			const refresherStatus = refresherCompleteDelay > 0 ? Enum.Refresher.Complete : Enum.Refresher.Default;

			refresherEnd(refresherStatus, () => {
				return delay(() => {
					let animateDuration = 1;
					const animateType = option.value.refresherEndBounceEnabled && fromAddData ? 'cubic-bezier(0.19,1.64,0.42,0.72)' : 'linear';
					if (fromAddData) {
						animateDuration = option.value.refresherEndBounceEnabled
							? Number(option.value.refresherCompleteDuration) / 1000
							: Number(option.value.refresherCompleteDuration) / 3000;
					}
					refresherTransition.value = `transform ${fromAddData ? animateDuration : Number(option.value.refresherDefaultDuration) / 1000}s ${animateType}`;
					// #ifndef APP-VUE || MP-WEIXIN || MP-QQ  || H5
					refresherTransform.value = 'translateY(0px)';
					currentDis = 0;
					// #endif
					// #ifdef APP-VUE || MP-WEIXIN || MP-QQ || H5
					wxsPropType.value = refresherTransition.value + 'end' + new Date().getTime();
					// #endif
					// #ifdef APP-NVUE
					_nRefresherEnd();
					// #endif
					moveDis = 0;
					// #ifndef APP-NVUE
					if (refresherStatus === Enum.Refresher.Complete) {
						if (refresherCompleteSubTimeout) {
							clearTimeout(refresherCompleteSubTimeout);
							refresherCompleteSubTimeout = undefined;
						}
						refresherCompleteSubTimeout = delay(() => {
							nextTick(() => {
								commonState.refresherStatus = Enum.Refresher.Default;
								isRefresherInComplete.value = false;
							});
						}, animateDuration * 800);
					}
					// #endif
					_emitTouchmove({ pullingDistance: 0, dy: moveDis });
				}, refresherCompleteDelay);
			});
			// #ifndef APP-NVUE
			if (refresherCompleteDelay > 0) {
				isRefresherInComplete.value = true;
			}
			// #endif
		}
		if (setLoading) {
			sleep(shouldEndLoadingDelay ? 100 : 0).then(() => {
				loading.value = false;
			});
			isUserPullDown && _onRestore();
		}
	};
	const refresherTransition = ref('');
	// 处理scroll-view bounce是否生效
	const handleScrollViewBounce = ({ bounce }: { bounce: boolean }) => {
		if (!option.value.usePageScroll && !option.value.scrollToTopBounceEnabled) {
			if (commonState.wxsScrollTop <= 5) {
				// #ifdef APP-VUE || MP-WEIXIN || MP-QQ || H5
				refresherTransition.value = '';
				// #endif
				commonState.scrollEnable = bounce;
			} else if (bounce) {
				commonState.scrollEnable = bounce;
			}
		}
	};
	// 终止下拉刷新状态
	const endRefresh = () => {
		_refresherEnd();
		handleScrollViewBounce({ bounce: true });
		nextTick(() => {
			refresherTriggered.value = false;
		});
	};
	watch(
		() => option.value.refresherEnabled,
		(v) => {
			// 当禁用下拉刷新时，强制收回正在展示的下拉刷新view
			!v && endRefresh();
		}
	);
	// 手动更新自定义下拉刷新view高度
	const updateCustomRefresherHeight = async () => {
		await sleep(100);
		nextTick(_updateCustomRefresherHeight);
	};

	// 处理列表触摸开始事件
	const handleListTouchstart = () => {
		if (option.value.useChatRecordMode && option.value.autoHideKeyboardWhenChat) {
			uni.hideKeyboard();
			emit('hidedKeyboard');
		}
	};
	// 进一步处理touch开始结果
	let refresherTouchstartY = 0;
	let lastRefresherTouchmove: { touchX: number; touchY: number };
	const handleRefresherTouchstart = (touch: ReturnType<typeof getTouch>) => {
		if (!loading.value && isTouchEnded.value) {
			isTouchmoving.value = false;
		}

		isTouchmovingTimeout && clearTimeout(isTouchmovingTimeout);
		isTouchEnded.value = false;
		refresherTransition.value = '';
		refresherTouchstartY = touch.touchY;
		emit('refresherTouchstart', refresherTouchstartY);
		lastRefresherTouchmove = touch;
		commonState.cleanAllTimeout();
	};
	const isTouchEnded = ref(false);
	// #ifndef APP-VUE || MP-WEIXIN || MP-QQ || H5

	// 判断touch手势是否要触发
	const touchDisabled = () => {
		const checkOldScrollTop = oldScrollTop.value > 5;
		return (
			loading.value ||
			isRefresherInComplete.value ||
			option.value.useChatRecordMode ||
			!option.value.refresherEnabled ||
			!option.value.useCustomRefresher ||
			(option.value.usePageScroll && option.value.useCustomRefresher && pageScrollTop.value > 10) ||
			(!(option.value.usePageScroll && option.value.useCustomRefresher) && checkOldScrollTop)
		);
	};
	

	// touch开始
	const _refresherTouchstart = (e: any) => {
		handleListTouchstart();
		console.log(touchDisabled())
		if (touchDisabled()) return;
		handleRefresherTouchstart(getTouch(e));
	};
	// #endif

	const refreshEnd = () => {
		commonState.refresherStatus = Enum.Refresher.Default;
	};

	// 进一步处理touch中结果
	const handleRefresherTouchmove = (_moveDis: number, touch: typeof lastRefresherTouchmove) => {
		refresherReachMaxAngle = true;
		isTouchmovingTimeout && clearTimeout(isTouchmovingTimeout);
		isTouchmoving.value = true;
		isTouchEnded.value = false;
		// 更新下拉刷新状态

		checkRefresherStatus(_moveDis >= finalRefresherThreshold.value, _moveDis);

		// #ifndef APP-VUE || MP-WEIXIN || MP-QQ  || H5
		// commonState.scrollEnable = false;
		// 通过transform控制下拉刷新view垂直偏移
		refresherTransform.value = `translateY(${_moveDis}px)`;
		lastRefresherTouchmove = touch;
		// #endif
		moveDis = _moveDis;
	};

	// 进一步处理touch结束结果
	const handleRefresherTouchend = (_moveDis: number) => {
		// #ifndef APP-PLUS || H5 || MP-WEIXIN
		if (!isTouchmoving.value) return;
		// #endif
		isTouchmovingTimeout && clearTimeout(isTouchmovingTimeout);
		refresherReachMaxAngle = true;
		isTouchEnded.value = true;
		const refresherThreshold = finalRefresherThreshold.value;
		if (_moveDis >= refresherThreshold && (commonState.refresherStatus === Enum.Refresher.ReleaseToRefresh || commonState.refresherStatus === Enum.Refresher.GoF2)) {
			// 如果是松手进入二楼状态，则触发进入二楼
			if (commonState.refresherStatus === Enum.Refresher.GoF2) {
				handleGoF2();
				_refresherEnd();
			} else {
				// 如果是松手立即刷新状态，则触发下拉刷新
				// #ifndef APP-VUE || MP-WEIXIN || MP-QQ || H5
				refresherTransform.value = `translateY(${refresherThreshold}px)`;
				refresherTransition.value = 'transform .1s linear';
				// #endif
				delay(() => {
					_emitTouchmove({ pullingDistance: refresherThreshold, dy: moveDis - refresherThreshold });
				}, 0.1);
				moveDis = refresherThreshold;
				commonState.refresherStatus = Enum.Refresher.Loading;
				_doRefresherLoad();
			}
		} else {
			_refresherEnd();
			isTouchmovingTimeout = delay(() => {
				isTouchmoving.value = false;
			}, Number(option.value.refresherDefaultDuration));
		}
		commonState.scrollEnable = true;
		emit('refresherTouchend', _moveDis);
	};
	let refresherReachMaxAngle = true;
	// wxs触摸方向改变
	const handleTouchDirectionChange = ({ direction }: { direction: string }) => {
		emit('touchDirectionChange', direction);
	};

	// 非appvue或微信小程序或QQ小程序或h5平台，使用js控制下拉刷新
	// #ifndef APP-VUE || MP-WEIXIN || MP-QQ || H5

	let oldCurrentMoveDis = 0;
	let currentDis = 0;
	// 获取处理后的moveDis
	const getFinalRefresherMoveDis = (_moveDis: number) => {
		let diffDis = _moveDis - oldCurrentMoveDis;
		oldCurrentMoveDis = _moveDis;
		if (diffDis > 0) {
			// 根据配置的下拉刷新用户手势位移与实际需要的位移比率计算最终的diffDis
			diffDis = diffDis * finalRefresherPullRate.value;
			if (currentDis > finalRefresherThreshold.value) {
				diffDis = diffDis * (1 - finalRefresherOutRate.value);
			}
		}
		// 控制diffDis过大的情况，比如进入页面突然猛然下拉，此时diffDis不应进行太大的偏移
		diffDis = diffDis > 100 ? diffDis / 100 : diffDis;
		currentDis += diffDis;
		currentDis = Math.max(0, currentDis);
		return currentDis;
	};

	let oldRefresherTouchmoveY = 0;
	let oldTouchDirection = ref('');
	let oldEmitedTouchDirection = ref('');
	let pullDownTimeStamp = 0;
	const disabledBounce = ref(false);
	// touch中
	const _refresherTouchmove = (e: any) => {
		const currentTimeStamp = new Date().getTime();
		let touch = null;
		let refresherTouchmoveY = 0;
		if (option.value.watchTouchDirectionChange) {
			// 检测下拉刷新方向改变
			touch = getTouch(e);
			refresherTouchmoveY = touch.touchY;
			const direction = refresherTouchmoveY > oldRefresherTouchmoveY ? 'top' : 'bottom';
			// 只有在方向改变的时候才emit相关事件
			if (direction === oldTouchDirection.value && direction !== oldEmitedTouchDirection.value) {
				handleTouchDirectionChange({ direction });
				oldEmitedTouchDirection.value = direction;
			}
			oldTouchDirection.value = direction;
			oldRefresherTouchmoveY = refresherTouchmoveY;
		}
		// 节流处理，在pullDownDisTimeStamp时间内的下拉刷新中事件不进行处理
		if (pullDownTimeStamp && currentTimeStamp - pullDownTimeStamp <= pullDownDisTimeStamp.value) return;
		// 如果不允许下拉，则return
		if (touchDisabled()) return;
		pullDownTimeStamp = Number(currentTimeStamp);
		touch = getTouch(e);
		refresherTouchmoveY = touch.touchY;
		// 获取当前touch的y - 初始touch的y，计算它们的差
		let moveDis = refresherTouchmoveY - refresherTouchstartY;
		if (moveDis < 0) return;
		// 对下拉刷新的角度进行限制
		if (
			Number(option.value.refresherMaxAngle) >= 0 &&
			Number(option.value.refresherMaxAngle) <= 90 &&
			lastRefresherTouchmove &&
			lastRefresherTouchmove.touchY <= refresherTouchmoveY
		) {
			if (!moveDis && !option.value.refresherAngleEnableChangeContinued && moveDis < 1 && !refresherReachMaxAngle) return;
			const x = Math.abs(touch.touchX - lastRefresherTouchmove.touchX);
			const y = Math.abs(refresherTouchmoveY - lastRefresherTouchmove.touchY);
			const z = Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2));
			if ((x || y) && x > 1) {
				// 获取下拉刷新前后两次位移的角度
				const angle = (Math.asin(y / z) / Math.PI) * 180;
				// 如果角度小于配置要求，则return
				if (angle < Number(option.value.refresherMaxAngle)) {
					lastRefresherTouchmove = touch;
					refresherReachMaxAngle = false;
					return;
				}
			}
		}
		// 获取最终的moveDis
		moveDis = getFinalRefresherMoveDis(moveDis);
		// 处理下拉刷新位移
		handleRefresherTouchmove(moveDis, touch);
		// 下拉刷新时，禁止页面滚动以防止页面向下滚动和下拉刷新同时作用导致下拉刷新位置偏移超过预期
		if (!disabledBounce.value) {
			// #ifndef MP-LARK
			handleScrollViewBounce({ bounce: false });
			// #endif
			disabledBounce.value = true;
		}
		_emitTouchmove({ pullingDistance: moveDis, dy: moveDis - oldMoveDis });
	};
	// touch结束
	const _refresherTouchend = (e: any) => {
		// 下拉刷新用户手离开屏幕，允许列表滚动
		handleScrollViewBounce({ bounce: true });
		if (touchDisabled() || !isTouchmoving.value) return;
		const touch = getTouch(e);
		let refresherTouchendY = touch.touchY;
		let moveDis = refresherTouchendY - refresherTouchstartY;
		moveDis = getFinalRefresherMoveDis(moveDis);
		handleRefresherTouchend(moveDis);
		disabledBounce.value = false;
	};
	// #endif

	const renderPropScrollTop = ref(-1);
	if ((option.value.usePageScroll && option.value.useChatRecordMode) || (!option.value.refresherEnabled && option.value.scrollable) || !option.value.useCustomRefresher) {
		nextTick(() => {
			renderPropScrollTop.value = 10;
		});
	}

	const wxsOnPullingDown = ref(false);

	// wxs正在下拉状态改变处理
	const handleWxsPullingDownStatusChange = (onPullingDown: boolean) => {
		wxsOnPullingDown.value = onPullingDown;
		if (onPullingDown && !option.value.useChatRecordMode) {
			renderPropScrollTop.value = 0;
		}
	};
	// wxs正在下拉处理
	const handleWxsPullingDown = (param: { moveDis: number; diffDis: number }) => {
		_emitTouchmove({ pullingDistance: param.moveDis, dy: param.diffDis });
	};

	const wxsPropType = ref('');
	// wxs通知更新其props
	const handlePropUpdate = () => {
		wxsPropType.value = new Date().getTime().toString();
	};

	// 模拟用户手动触发下拉刷新
	const doRefresherRefreshAnimate = () => {
		commonState.cleanRefresherCompleteTimeout();
		// 用户处理用户在短时间内多次调用reload的情况，此时下拉刷新view不需要重复显示，只需要保证最后一次reload对应的请求结束后收回下拉刷新view即可
		// #ifndef APP-NVUE
		const _doRefreshAnimateAfter = !doRefreshAnimateAfter.value && customRefresherHeight.value === -1 && option.value.refresherThreshold === _addUnit(80, option.value.unit);
		if (_doRefreshAnimateAfter) {
			doRefreshAnimateAfter.value = true;
			return;
		}
		// #endif
		refresherRevealStackCount.value++;
		// #ifndef APP-VUE || MP-WEIXIN || MP-QQ  || H5
		refresherTransform.value = `translateY(${finalRefresherThreshold.value}px)`;
		// #endif
		// #ifdef APP-VUE || MP-WEIXIN || MP-QQ || H5
		wxsPropType.value = 'begin' + new Date().getTime();
		// #endif
		moveDis = finalRefresherThreshold.value;
		commonState.refresherStatus = Enum.Refresher.Loading;
		isTouchmoving.value = true;
		isTouchmovingTimeout && clearTimeout(isTouchmovingTimeout);
		_doRefresherLoad(false);
	};

	// 更新自定义下拉刷新view高度
	const _updateCustomRefresherHeight = () => {
		// #ifndef APP-NVUE
		getRect(ctx, '.e-scroll-view__custom-refresher-slot-view').then((size) => {
			customRefresherHeight.value = size.height || 0;
			showCustomRefresher.value = customRefresherHeight.value > 0;
			if (doRefreshAnimateAfter.value) {
				doRefreshAnimateAfter.value = false;
				doRefresherRefreshAnimate();
			}
		});
		// #endif
	};

	onMounted(() => {
		wxsPropType.value = new Date().getTime().toString();
	});
	return {
		pullDownDisTimeStamp,
		privateRefresherEnabled,
		refresherThresholdUnitConverted,
		finalRefresherEnabled,
		finalRefresherThresholdPlaceholder,
		finalRefresherThreshold,
		finalRefresherF2Threshold,
		finalRefresherFixedBacHeight,
		finalRefresherThemeStyle,
		finalRefresherOutRate,
		finalRefresherPullRate,
		finalRefresherTransform,
		finalRefresherTriggered,
		showRefresher,
		refresherTransform,
		refresherRevealStackCount,
		refresherTriggered,
		isTouchmoving,
		customRefresherHeight,
		showCustomRefresher,
		doRefreshAnimateAfter,
		isRefresherInComplete,
		_onRestore,
		loading,
		_refresherEnd,
		refresherTransition,
		handleScrollViewBounce,
		endRefresh,
		updateCustomRefresherHeight,
		handleRefresh,
		finalRefresherDefaultStyle,
		handleListTouchstart,
		handleRefresherTouchstart,
		handleTouchDirectionChange,
		isTouchEnded,
		// #ifndef APP-VUE || MP-WEIXIN || MP-QQ || H5
		touchDisabled,
		getFinalRefresherMoveDis,
		_emitTouchmove,
		oldTouchDirection,
		oldEmitedTouchDirection,
		disabledBounce,
		_refresherTouchmove,
		_refresherTouchend,
		// #endif
		refreshEnd,
		handleRefresherTouchmove,
		handleRefresherTouchend,
		renderPropScrollTop,
		wxsOnPullingDown,
		handleWxsPullingDownStatusChange,
		handleWxsPullingDown,
		wxsPropType,
		handlePropUpdate,
		showF2,
		f2Transform,
		f2ElRef,
		nF2Opacity,
		handleGoF2,
		_handleCloseF2,
		closeF2,
		doRefresherRefreshAnimate,
		_doRefresherLoad,
		_updateCustomRefresherHeight,
		// #ifdef APP-NVUE
		nLoadingMoreFixedHeight,
		finalNvueListIs,
		nWaterfallColumnCount,
		nWaterfallColumnWidth,
		nWaterfallColumnGap,
		nWaterfallLeftGap,
		nWaterfallRightGap,
		nViewIs,
		finalNvueSuperListIs,
		finalNvueRefresherEnabled,
		handleNVueScroll,
		nListRef,
		_nRefresherEnd,
		nRefresherLoading,
		_nOnRrefresh,
		_nOnPullingdown,
		_nDoRefresherEndAnimation,
		handleNVueLoadmore,
		_nGetWaterfallConfig
		// #endif
	};
};

export default useRefresher;
